package com.heima.zhuangshi;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class ProxyTest {
    public static void main(String[] args) {

        //获取奶茶对象- 上奶茶
        MyTea myTea = new MyTea();
        myTea.zuo();
        myTea.getTea();

        //代理对象
        //ClassLoader loader,   加载这个对象的类加载器
        //Class[] interfaces,   这个对象的接口类型
        //InvocationHandler h   处理规则（代理规则）
        //proxyTea  代理后的对象  ==hongTea
        Tea proxyTea = (Tea) Proxy.newProxyInstance(myTea.getClass().getClassLoader(),
                new Class[] {Tea.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("执行大方法为=" + method.getName());
                        System.out.println(Arrays.toString(args));
                        if (method.getName().equals("getTea")) {
                            //代理...
                            System.out.println("加冰");
                            method.invoke(myTea);
                            System.out.println("不要牛奶");
                            return null;
                        } else {
                            method.invoke(myTea);
                            return proxy;
                        }
                    }
                }
        );

        //执行对象代码
        System.out.println("------------");
        proxyTea.zuo();
        proxyTea.getTea();
        proxyTea.getTea("绿豆");
    }
}
